package org.icnmasjid.member.util;

import java.util.List;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.Constants;

public class CommonUtil {
	
	public static void send(String from, String to, String cc, String subject, String content)
	throws AddressException, MessagingException
	{
		send(from, new String[]{to}, cc != null ? new String[]{cc} : null, subject, content);
	}
	
	public static void send(String from, String[] to, String[] cc, String subject, String content)
	throws AddressException, MessagingException
	{
		// Create a mail session
		java.util.Properties props = new java.util.Properties();
		props.put("mail.smtp.host", Constants.SMTP_HOST);
		props.put("mail.smtp.port", "" + Constants.SMTP_PORT);
		Session session = Session.getDefaultInstance(props, null);

		// Construct the message
		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(from));
		for (String toEmail: to) {
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
		}
		if ( cc != null ) {
			for (String ccEmail: cc) {
				msg.addRecipient(Message.RecipientType.CC, new InternetAddress(ccEmail));
			}
		}
		msg.setSubject(subject);
		msg.setContent(content, "text/html");

		// Send the message
		Transport.send(msg);
	}
	


	public static void send(String to, String subject, String content)
	throws AddressException, MessagingException
	{
		send(Constants.EMAIL_FROM, to, null, subject, content);
	}
	
    public static String buildCSV(List<String> list) {
    	StringBuffer sb = new StringBuffer();
    	for ( String s: list) {
    		sb.append(s);
    		sb.append(",");
    	}
    	if ( sb.length() > 0) {
    		sb.deleteCharAt(sb.length()-1);
    	}
    	return sb.toString();
    }
}
